@echo off

REM Set project path
SET PROJECT_PATH=d:\_dproject\buildproject\05HarmonyOS\project\node-server

REM Try different MySQL service names (common for phpstudy_pro)
SET MYSQL_SERVICES[0]="MySQL8.0"
SET MYSQL_SERVICES[1]="MySQLa"
SET MYSQL_SERVICES[2]="MySQL8"
SET MYSQL_SERVICES[3]="phpstudyMySQL8"

REM Check and start MySQL service
echo Checking MySQL service status...
SET "FOUND_SERVICE="
SET "SERVICE_RUNNING="

FOR /L %%i IN (0,1,3) DO (
    FOR /F "tokens=2 delims==" %%a IN ('set MYSQL_SERVICES[%%i]') DO (
        SET "CURRENT_SERVICE=%%~a"
        echo Checking service %%~a...
        sc query "%%~a" > nul
        IF %ERRORLEVEL% EQU 0 (
            SET "FOUND_SERVICE=%%~a"
            echo MySQL service found: %%~a
            sc query "%%~a" | findstr "RUNNING" > nul
            IF %ERRORLEVEL% EQU 0 (
                SET "SERVICE_RUNNING=1"
                echo MySQL service %%~a is already running
                GOTO :SERVICE_CHECK_DONE
            ) ELSE (
                echo MySQL service %%~a is installed but not running
                GOTO :SERVICE_CHECK_DONE
            )
        )
    )
)

:SERVICE_CHECK_DONE

REM If service found but not running, try to start it
IF DEFINED FOUND_SERVICE (
    IF NOT DEFINED SERVICE_RUNNING (
        echo Starting MySQL service: %FOUND_SERVICE%...
        net start "%FOUND_SERVICE%"
        IF %ERRORLEVEL% EQU 0 (
            echo MySQL service %FOUND_SERVICE% started successfully
        ) ELSE (
            echo Failed to start MySQL service %FOUND_SERVICE%
            echo Please manually start phpstudy_pro and enable MySQL service
            pause
        )
    )
) ELSE (
    echo MySQL service not found
    echo Please ensure phpstudy_pro is properly installed and MySQL service is configured
    echo It's recommended to manually start the phpstudy_pro control panel and enable MySQL service
    pause
)


REM Switch to project directory
echo Changing to project directory...
cd /d %PROJECT_PATH%

REM Start Node.js server
echo Starting Node.js server...
npm start

pause